package com.edushare.common.dao;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.apache.cayenne.DataObjectUtils;
import org.apache.cayenne.exp.Expression;
import org.apache.cayenne.query.SelectQuery;
import org.apache.cayenne.query.SortOrder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.wicket.util.file.File;

import com.edushare.common.orm.ORMInterface;
import com.edushare.common.util.StringUtil;
import com.edushare.common.util.SystemUtils;
import com.edushare.common.vo.FileDirectories;
import com.edushare.common.vo.FilesUploaded;
import com.edushare.common.vo.Users;

public class FilesUploadedDAO extends CayenneBasedDAO {
	
	private static Log log = LogFactory.getLog(FilesUploadedDAO.class);

	public FilesUploadedDAO(ORMInterface ormInterface) {
		super(ormInterface);
	}
	
	@SuppressWarnings("unchecked")
	public List<FilesUploaded> getFilesUploaded(FileDirectories fileDirectory, int privacyType){
		Expression exp = Expression.fromString("fileDirectory = $filedir and permissionType = $permtype");
		HashMap params = new HashMap();
		params.put("filedir", fileDirectory);
		params.put("permtype", privacyType);
		
		SelectQuery query = new SelectQuery(FilesUploaded.class, exp.expWithParameters(params));
		return (List<FilesUploaded>)getDataContext().performQuery(query);
	}

	@SuppressWarnings("unchecked")
	public List<FilesUploaded> getFilesUploadedByUser(FileDirectories fileDirectory,
			Users user, Integer filePermissionType) {
		Expression exp = Expression.fromString("fileDirectory = $filedir and permissionType = $permtype and uploader = $usr");
		HashMap params = new HashMap();
		params.put("filedir", fileDirectory);
		params.put("permtype", filePermissionType);
		params.put("usr", user);
		
		SelectQuery query = new SelectQuery(FilesUploaded.class, exp.expWithParameters(params));
		return (List<FilesUploaded>)getDataContext().performQuery(query);
	}
	
	//TODO: work this out -- Nishant
	/*public List<Users> getContributingUsers(FileDirectories fileDirectory, int pageSize){
		return getContributingUsers(fileDirectory, 0, pageSize);
	}*/
	
	@SuppressWarnings("unchecked")
	public List<Users> getContributingUsers(FileDirectories fileDirectory, int filePermissionType, int pageSize){
		
		String qualifierString = "fileDirectory = $filedir";
		/*if(filePermissionType == 0){
			qualifierString = qualifierString + " and permissionType = $permtype";
		}*/
		qualifierString = "filesUploaded.fileDirectory = $filedir and filesUploaded.permissionType = $permType";
		Expression exp = Expression.fromString(qualifierString);
		HashMap params = new HashMap();
		params.put("filedir", fileDirectory);
		params.put("permType", filePermissionType);
		
		SelectQuery query = new SelectQuery(Users.class, exp.expWithParameters(params));
		query.setPageSize(pageSize);
		query.addOrdering("firstName", SortOrder.ASCENDING);
		return (List<Users>)getDataContext().performQuery(query);
	}

	public void deleteFiles(List<FilesUploaded> filesUploadedList) {
		if(filesUploadedList == null || filesUploadedList.size()<1)
			return;
		Iterator<FilesUploaded> it = filesUploadedList.iterator();
		
		while(it.hasNext()){
			FilesUploaded currObj = it.next();
			deleteFileFromStorage(currObj);
			it.remove();
			getDataContext().deleteObject(currObj);
			getDataContext().commitChanges();//shouldnt be necessary
		}
		
	}

	public void deleteFileUploaded(FilesUploaded fileUploaded) {
		deleteFileFromStorage(fileUploaded);
		getDataContext().deleteObject(fileUploaded);
	}
	
	/** this deletes files from media directory only */
	private void deleteFileFromStorage(FilesUploaded fileUploaded) {
		if(fileUploaded == null)
			return;
		String basePath = SystemUtils.getRootDirectoryPath();
		if(StringUtil.isValid(fileUploaded.getFileRelativePath())){
			String relpath = fileUploaded.getFileRelativePath();
			if(relpath.startsWith("//")||relpath.startsWith("\\")){
				relpath = relpath.substring(1);
			}
			
			String completePath = basePath + "/" + relpath;
			log.info("DELETING FILE: "+ completePath);
			try{
				File file = new File(completePath);
				file.delete();
			}catch(Exception e){
				log.fatal("ERROR DELETING FILE: "+ completePath, e);
			}
		}
	}

	@SuppressWarnings("unchecked")
	public List<FilesUploaded> getFilesUploadedByUser(FileDirectories dir,Users loggedInUser) {
		Expression exp = Expression.fromString("fileDirectory = $filedir and uploader = $usr");
		HashMap params = new HashMap();
		params.put("filedir", dir);
		params.put("usr", loggedInUser);
		
		SelectQuery query = new SelectQuery(FilesUploaded.class, exp.expWithParameters(params));
		return (List<FilesUploaded>)getDataContext().performQuery(query);
	}

	public FilesUploaded getFileById(int fileId) {
		return DataObjectUtils.objectForPK(getDataContext(), FilesUploaded.class, fileId);
	}

	public List<FilesUploaded> getFiles(FileDirectories fileDir) {
		return fileDir.getFilesUploaded();
	}

}
